// ==UserScript==
// @name	eCompany
// @version	0.0.1
// @description	eCompany
// @author	eCompany
// @namespace	eCompany
// @include	http://*.erepublik.com/en
// @include	http://erepublik.com/en
// @require	http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// @require	http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js
// ==/UserScript==

$('#shouts').before('<table id="markerOffers" border="1" width="100%"><tr><td><img src="/images/parts/ajax-loader.gif"/></td></tr></table>');

var profile = $("div.core div.avatarholder a").attr("href");

var req = new XMLHttpRequest();
var companies = {};
var countries = null;
var token = $("#_token").attr('value');

var PRODUCTS = {
	"food"				:	{"raw_type"		:	"grain",
							 "raw_needed"	:	"1",
							 "rec_employee"	:	"10",
							 "short"		:	"FOO",
							 "id"			:	"1"},
	"gift"				:	{"raw_type"		:	"diamonds",
							 "raw_needed"	:	"2",
							 "rec_employee"	:	"10",
							 "short"		:	"GI",
							 "id"			:	"2"},
	"weapon"			:	{"raw_type"		:	"iron",
							 "raw_needed"	:	"5",
							 "rec_employee"	:	"10",
							 "short"		:	"WEA",
							 "id"			:	"3"},
	"moving tickets"	:	{"raw_type"		:	"oil",
							 "raw_needed"	:	"10",
							 "rec_employee"	:	"10",
							 "short"		:	"MTI",
							 "id"			:	"4"},
	"house"				:	{"raw_type"		:	"wood",
							 "raw_needed"	:	"200",
							 "rec_employee"	:	"20",
							 "short"		:	"HOU",
							 "id"			:	"10"},
	"hospital"			:	{"raw_type"		:	"wood",
							 "raw_needed"	:	"2000",
							 "rec_employee"	:	"20",
							 "short"		:	"HOS",
							 "id"			:	"11"},
	"defense system"	:	{"raw_type"		:	"wood",
							 "raw_needed"	:	"2000",
							 "rec_employee"	:	"20",
							 "short"		:	"DES",
							 "id"			:	"12"},
	"grain"				:	{"rec_employee"	:	"10",
							 "short"		:	"GRA",
							 "id"			:	"5"},
	"diamonds"			:	{"rec_employee"	:	"10",
							 "short"		:	"DIA",
							 "id"			:	"6"},
	"iron"				:	{"rec_employee"	:	"10",
							 "short"		:	"IRO",
							 "id"			:	"7"},
	"oil"				:	{"rec_employee"	:	"10",
							 "short"		:	"OIL",
							 "id"			:	"8"},
	"wood"				:	{"rec_employee"	:	"10",
							 "short"		:	"WOO",
							 "id"			:	"9"}
};

function getCountryId(country) {
	var id = -1;
	$(countries).find("country").each(function() {
		if(country == $("name",this).text())  {
			id = $("id",this).text();
		}
	});
	return id;
}

GM_xmlhttpRequest({
	method: "GET",
	url: "http://api.erepublik.com/v1/feeds/countries",
	onload: function(response) {
		//countries = new DOMParser().parseFromString(response.responseText, "text/xml");
		countries = response.responseText;
		StartCompanyOffers();
	}
});

function StartCompanyOffers()  {
	count = 0;
	shown = 0;
	try {
		req.open("GET", "http://www.erepublik.com"+profile, true);
		req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
		req.setRequestHeader('Referer',window.location.href);
		req.onreadystatechange = 
			function(  ) {
				//var req = event.target;
				if( (req.readyState == 4) && ( req.status == 200 || req.status == 0 ) ) {
					var companyList = $('#career_tab_content div.quarter:first a.dotted', req.responseText);
					if (companyList.size()>0) {
						$('#markerOffers').html('<tr>'
							+'<th>Cou</th>'
							+'<th>Comp</th>'
							+'<th>Stock</th>'
							+'<th>Mark</th>'
							+'<th>Net</th>'
							+'<th>Best</th>'
							//+'<th>Vat</th>'
							+'<th>New</th>'
							+'<th>Set</th>'
							+'</tr>');
						companyList.each(
							function (i) {
								var parts = $(this).attr('href').split('-');
								var cid = parts[parts.length-1]; 
								$('#markerOffers').append(
									'<tr id="companyNr'+cid+'"></tr>');
								companies['c'+cid]={};
								companies['c'+cid].href=$(this).attr('href');
								companies['c'+cid].title=$(this).attr('title');
								companies['c'+cid].cid=cid;
								companies['c'+cid].details = companies['c'+cid].href.replace("/company/", "/company-details/");
								companyInfo(cid);
								count++;
							}
						)
					} else {
						$('#markerOffers').html('Nem találtam céget');
					}
				}
			}
		req.send(null);
	} catch( e ) {throw e;}
}
			
function companyInfo(cid) {
	GM_xmlhttpRequest({
		method: 'GET',
		url: 'http://api.erepublik.com/v1/feeds/companies/'+cid,
		onload: function (resp) {
			var dom = new DOMParser().parseFromString(resp.responseText, "text/xml");
			companies['c'+cid].country = $(dom).find("company > country").text();
			companies['c'+cid].countryid = getCountryId(companies['c'+cid].country);
			companies['c'+cid].industry = $(dom).find("company > industry").text();
			companies['c'+cid].quality = $(dom).find("company > quality").text();
			companies['c'+cid].domain = $(dom).find("company > domain").text();
			showCompany(cid);
			companyDetails(cid);
		}
	});
}

function companyDetails(cid) {
	var detReq = new XMLHttpRequest();
	var url = "http://www.erepublik.com"+companies['c'+cid].details;
	detReq.id = cid;
	try {
		detReq.open("GET", url, true);
		detReq.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
		req.setRequestHeader('Referer',"http://www.erepublik.com"+companies['c'+cid].href);
		detReq.onreadystatechange = 
			function(  ) {
				//var req = event.target;
				if( (detReq.readyState == 4) && ( detReq.status == 200 || detReq.status == 0 ) ) {
					//var dom = new DOMParser().parseFromString(detReq.responseText, "text/html");
					var txt = '<div>'+detReq.responseText+'</div>';
					var v = $("#market_offers tr:gt(0)", txt);
/*					
					GM_log('aaa: '+companies['c'+cid].country+','+v.size()
					+','+$('#sf_culture',txt).size()
					+','+$('#market_offers',txt).size()
					//+','+$('div.left:has(img[alt="Stock"])',txt).size()
					//+"\n"+txt
					);
*/				
					v.each(function() {
//						GM_log($("img",this).attr("title")+' vs '+companies['c'+cid].country);
						if($("img",this).attr("title") == companies['c'+cid].country) {
							var ammountTag =   $("input.ammount:first",this);
							if (ammountTag.size()==1) {
								companies['c'+cid].ammount = ammountTag.attr('value')*1;
								var nettoid
								var offerid = ammountTag.attr('id').replace('amount_','');
								companies['c'+cid].offerid = offerid;
								companies['c'+cid].netto = $("#price_"+offerid,this).attr('value')*1;
								if (companies['c'+cid].domain=='land') {
									companies['c'+cid].brutto = companies['c'+cid].netto;
									companies['c'+cid].vat = 0;
								} else {
									companies['c'+cid].brutto = $("#price_with_taxes_"+offerid,this).text()*1;
									companies['c'+cid].vat = $("#taxes_"+offerid,this).attr('value')*1;
								}
							}
						}
					});
					companies['c'+cid].stock = $('#number_of_products', txt).text()*1;
					showCompany(cid);
					marketOffers(cid);
					
				}
			}
		detReq.send(null);
	} catch( e ) {throw e;}
}

function marketOffers(cid) {
	/*
	var maoReq = new XMLHttpRequest();
	var url = "http://www.erepublik.com/en/market/country-"+companies['c'+cid].countryid+"-industry-"+PRODUCTS[companies['c'+cid].industry]["id"]+"-quality-"+companies['c'+cid].quality+'/1;
	GM_log(url);
	maoReq.id = cid;
	try {
		maoReq.open("GET", url, true);
		maoReq.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
		maoReq.onreadystatechange = 
			function(  ) {
				//var req = event.target;
				if( (maoReq.readyState == 4) && ( maoReq.status == 200 || maoReq.status == 0 ) ) {
					//var dom = new DOMParser().parseFromString(detReq.responseText, "text/html");
					var txt = '<div>'+maoReq.responseText+'</div>';
					GM_log(url+"\n"+txt);
					showCompany(cid);
				}
			}
		detReq.send(null);
	} catch( e ) {throw e;}
	*/
	var sReq = "http://api.erepublik.com/v1/feeds/market/";
	var url = (sReq + companies['c'+cid].industry.replace(/ /g, "-")+'/'+companies['c'+cid].quality+'/'+companies['c'+cid].country.replace(/ /g, "-")).toLowerCase();
	GM_xmlhttpRequest({ 
		method: 'GET',
		url: url,
		onload: function (response) {
			var dom = new DOMParser().parseFromString(response.responseText, "text/xml");
			var first = true;
			var brutto = -1;
			var netto = -1;
			$("record", dom).each(function() {
				if (brutto==-1 && $('is-a-company', this).text()!=cid) {
					brutto= parseFloat($('price',this).text());
					netto = Math.round(brutto/(1+companies['c'+cid].vat)*100)/100;
				}
			});
			companies['c'+cid].bestNetto = netto;
			companies['c'+cid].bestBrutto = brutto;
			if (companies['c'+cid].domain=='land') {
				companies['c'+cid].newPrice = companies['c'+cid].bestNetto;
			} else {
				if ( netto>1002) {
					companies['c'+cid].newPrice = companies['c'+cid].bestNetto - 2 ;
				} else if ( netto>100.2) {
					companies['c'+cid].newPrice = companies['c'+cid].bestNetto - 0.2 ;
				} else {
					companies['c'+cid].newPrice = companies['c'+cid].bestNetto - 0.02 ;
				};
			}
			companies['c'+cid].newPrice = Math.round(companies['c'+cid].newPrice*100)/100;
			showCompany(cid);
		}
	});
}

function showCompany(cid) {
	$('#companyNr'+cid).html(
	'<td><img height="11" width="15" src="/images/flags/L/'+companies['c'+cid].country+'.gif"></td>'
	+'<td><a href="'+companies['c'+cid].href+'">'+PRODUCTS[companies['c'+cid].industry].short+companies['c'+cid].quality+'</a></td>'
	+'<td>'+companies['c'+cid].stock+'</td>'
	+'<td>'+companies['c'+cid].ammount+'</td>'
	+'<td>'+companies['c'+cid].netto+'</td>'
	+'<td>'+companies['c'+cid].bestNetto+'</td>'
	//+'<td>'+companies['c'+cid].vat+'</td>'
	+'<td>'+companies['c'+cid].newPrice+'</td>'
	+'<td id="sendOffer'+cid+'" style="cursor:pointer">set</td>'
	);
	$('#sendOffer'+cid).click( function () {
		setOffer(companies['c'+this.id.substring(9)]);
	});
	shown++;
	if (shown == count) {
		$('#markerOffers').append('<tr id="setalloffer"  style="cursor:pointer"><td colspan="100%" align="center">Set All Offer</td></tr>');
		$('#setalloffer').click(function () {
			sent = 0;
			for(key in companies) {
				setOffer(companies[key]);
			}
		})
	}
}


function setOffer(comp) {
	var url_page = "/en/market_offer_ajax/";
	url_page += token+"/"+comp.cid+"/";
	url_page += comp.offerid+"/";
	url_page += (comp.stock+comp.ammount)+"/";
	url_page += comp.newPrice+"/"+(comp.ammount>0?"update":"new");
	GM_log(url_page)
	var detReq = new XMLHttpRequest();
	try {
		detReq.id = comp.cid;
		detReq.open("GET", url_page, true);
		detReq.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
		detReq.setRequestHeader('Referer',"http://www.erepublik.com"+companies['c'+comp.cid].href);
		detReq.onreadystatechange = 
			function(  ) {
				//var req = event.target;
				if( (detReq.readyState == 4) && ( detReq.status == 200 || detReq.status == 0 ) ) {
					companyDetails(detReq.id);
				}
			}
		detReq.send(null);
	} catch( e ) {throw e;}
}
